const jwt = require('jsonwebtoken')
const config = require("../config")
const {
    notFound
} = require("../core/http-exception")
const routerAuth = require('../utils/routerAuth')

class Auth {
    constructor(level) {
        //简易的权限分级
        this.level = level || 1
        Auth.user = 2
        Auth.admin = 6
    }
    get m() {
        return async (ctx, next) => {
            //不需要令牌处理方案
            if (this.urlAuth(ctx.request.url)) {
                await next()
                return false
            }
            //需要令牌处理方案
            const token = ctx.header.token
            if (!token) {
                throw new notFound('令牌不存在！', 10006)
            }
            try {
                var decode = jwt.verify(token, config.refreshToken.secretKey)
                
            } catch (error) {
                if (error.name == 'TokenExpiredError') {
                    throw new notFound('令牌已过期', 10007)
                }
                throw new notFound('令牌不合法！', 10006)
            }
            if (decode.scope < this.level) {
                throw new notFound('用户权限不足！', 10008)
            }
            ctx.auth = {
                uid: decode.uid,
                scope: decode.scope
            }
            await next()
        }
    }
    urlAuth(url) {
        let auth = routerAuth.find(item => {
            return item.url == url.split('?')[0];
        })
        return auth
    }
}
module.exports = Auth